from . import default
import copy

class Scope(object):

    def __init__(self, name='', father_scope=None, is_root=False):
        '''
        Example:
        __scope_list = ['train', 'first_layer']
        '''
        if is_root:
            self.__scope_list = []
            self.father_scope = None
            return
        if father_scope is None:
            father_scope = default.scope
        self.__scope_list = copy.copy(father_scope.__scope_list)
        self.father_scope = father_scope
        assert isinstance(name, str)
        assert name != ''
        assert '/' not in name
        self.__scope_list.append(name)

    def __str__(self):
        if self.__scope_list == []:
            return ''
        else:
            return '/'.join(self.__scope_list) + '/'

    def __enter__(self):
        self.__previous_default_scope = default.scope
        default.scope = self
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        default.scope = self.__previous_default_scope
        if exc_tb is not None:
            return False
        else:
            return True

default.scope = Scope(is_root=True)